package com.xhx.controller;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 生成pdf
 * 
 * @author xhx
 */
@RestController
@Slf4j
@RequestMapping("/pdf/gen")
public class GeneratePdfController extends AbstractPdfController {

	private static List<String> SUFS = Arrays.asList("png", "jpg", "jpeg", "gif", "bmp");

	public GeneratePdfController() {
		super(log);
	}

	/**
	 * 将路径里面的所有图片拼接到pdf
	 * 
	 * @param path
	 * @param name
	 * @return
	 */
	@GetMapping("/generateByPath")
	public String generateByPath(@RequestParam String path, @RequestParam String name,
			@RequestParam(defaultValue = "0.5") Float scaleFactor) {
		File dir = new File(path);
		if (!dir.exists() || !dir.isDirectory()) {
			return "路径不争取";
		}
		File[] files = dir.listFiles(checkImageFile());
		if (files == null || files.length == 0) {
			return "路径下无pdf";
		}
		List<File> imagePaths = Stream.of(files).collect(Collectors.toList());

		String outputPdfPath = path + File.separator + name;

		convertImagesToPdf(imagePaths, outputPdfPath, scaleFactor);

		return String.format("已处理%s个文件", files.length);
	}

	private FilenameFilter checkImageFile() {
		return (d, n) -> {
			for (String s : SUFS) {
				if (n.toLowerCase().endsWith(s)) {
					return true;
				}
			}
			return false;
		};
	}

	public static void convertImagesToPdf(List<File> imagePaths, String outputPath, float scaleFactor) {
		try (PDDocument document = new PDDocument()) {
			for (File imageFile : imagePaths) {
				// 加载图片文件
				PDImageXObject pdImage = PDImageXObject.createFromFileByContent(imageFile, document);

				// 创建A4页面（可根据需要修改尺寸）
				PDPage page = new PDPage(PDRectangle.A4);
				document.addPage(page);

				float targetWidth = pdImage.getWidth() * scaleFactor;
				float targetHeight = pdImage.getHeight() * scaleFactor;

				float x = (page.getMediaBox().getWidth() - targetWidth) / 2;
				float y = (page.getMediaBox().getHeight() - targetHeight) / 2;

				try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
					contentStream.drawImage(pdImage, x, y, targetWidth, targetHeight);
				}
			}

			// 保存PDF文件
			document.save(outputPath);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
	}

}
